package com.share.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

/**
 * author caifan
 * date 2020/10/22
 * description: 将json中的key大写转成驼峰
 */
public class JsonConvertUtils {


    /**
     * 将json的key转成驼峰格式，现在只处理大写开头和包含_的
     *
     * @param json
     * @return
     */
    public static JSONObject jsonKeyToCamel(JSONObject json) {
        return jsonKeyToCamel(json, true);
    }

    /**
     * 将json的key转成驼峰格式，现在只处理大写开头和包含_的
     *
     * @param json
     * @param flag 默认为true 转成驼峰格式，false则将首字母转成大写
     * @return
     */
    public static JSONObject jsonKeyToCamel(JSONObject json, Boolean flag) {
        if (Objects.isNull(json)) {
            return null;
        }
        JSONObject newJson = new JSONObject();
        for (JSONObject.Entry<String, Object> obj : json.entrySet()) {
            String key = getCamelKey(obj.getKey(), flag);
            if (Objects.isNull(obj.getValue())) {
                newJson.put(key, null);
            } else {
                if (obj.getValue() instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) obj.getValue();
                    newJson.put(key, jsonKeyToCamel(jsonObject, flag));
                } else if (obj.getValue() instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) obj.getValue();
                    JSONArray newJsonArray = new JSONArray();
                    for (Object objArray : jsonArray) {
                        if (objArray instanceof JSONObject) {
                            JSONObject jsonObject = (JSONObject) objArray;
                            newJsonArray.add(jsonKeyToCamel(jsonObject, flag));
                        } else {
                            newJsonArray.add(objArray);
                        }
                    }
                    newJson.put(key, newJsonArray);
                } else {
                    newJson.put(key, obj.getValue());
                }
            }
        }
        return newJson;
    }

    /**
     * 将含_的转成大写 首字母大写的转小写
     *
     * @param key
     * @param flag
     * @return
     */
    private static String getCamelKey(String key, Boolean flag) {
        if (key.contains("_")) {
            StringBuffer buffer = new StringBuffer();
            String[] splitKeys = key.split("_");
            buffer.append(splitKeys[0]);
            for (int i = 1; i < splitKeys.length; i++) {
                if (Character.isLowerCase(splitKeys[i].charAt(0))) {
                    if (splitKeys[i].length() > 1) {
                        buffer.append(Character.toUpperCase(splitKeys[i].charAt(0))).append(splitKeys[i].substring(1));
                    } else {
                        buffer.append(Character.toUpperCase(splitKeys[i].charAt(0)));
                    }
                } else {
                    buffer.append(splitKeys[i]);
                }
            }
            key = buffer.toString();
        }
        if (flag) {
            key = Character.toLowerCase(key.charAt(0)) + (key.substring(1));
        } else {
            key = Character.toUpperCase(key.charAt(0)) + (key.substring(1));
        }
        return key;
    }

    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("abc", "zhangsan");
        json.put("birth", new Date());
        json.put("my_ide", "idea");
        json.put("MySalary", BigDecimal.valueOf(1000.23));
        JSONObject myJson = new JSONObject();
        myJson.put("name", "lisi");
        myJson.put("Age", 33);
        myJson.put("home_address", "上海");
        json.put("MyJson", myJson);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(myJson);
        json.put("myArray", jsonArray);
//        JSONObject jsonObject = jsonKeyToCamel(json, false);
//        System.out.println(jsonObject.toJSONString());

        JSONObject jsonObject = JSON.parseObject("{\"status\":true,\"code\":1,\"msg\":\"查询成功\",\"data\":{\"carId\":null,\"isPost\":null,\"isUrgent\":null,\"canUrgent\":null,\"carNumber\":\"川AG1T16\",\"carCode\":null,\"carDriver\":null,\"isUseActiveprice\":null,\"urgentAmount\":0.0,\"usedCoupon\":2,\"urgentFlag\":2,\"phone\":null,\"orderPoundage\":null,\"orderFineAmount\":0.0,\"voliationCount\":null,\"orderScore\":null,\"jiaShiZhenID\":null,\"drivingLicense\":null,\"drivingFileNumber\":null,\"drivingPhoneNumber\":null,\"totalDegree\":null,\"totalFine\":null,\"totalVoliationCount\":null,\"invalidTime\":null,\"cardNumber\":null,\"ollectFees\":0,\"payPoundge\":null,\"couponCanDiscountFee\":null,\"permitCouponCount\":0,\"payType\":0,\"extention\":{\"cardTypeId\":\"YearCar\",\"vipStatus\":0},\"Items\":[{\"violationId\":null,\"backendId\":5484536626071125446,\"carId\":null,\"carNumber\":null,\"occurTime\":\"2020-05-2811:52:47\",\"location\":null,\"reason\":null,\"fine\":0.0,\"status\":null,\"department\":null,\"degree\":\"0\",\"violationCode\":\"6050\",\"archive\":null,\"telephone\":null,\"executeLoaction\":null,\"executeDepartment\":null,\"category\":null,\"illegalentry\":null,\"locaitonId\":\"6101\",\"locationName\":null,\"dataSourceId\":null,\"recordType\":null,\"lateFine\":null,\"punishMentAccording\":null,\"pounDage\":null,\"other\":\"0\",\"cooperPoundge\":\"59.0\",\"canProcess\":null,\"canProcessMsg\":null,\"uniqueCode\":null,\"violationStatus\":null,\"needXingshizheng\":null,\"needJiashizheng\":null,\"localUniqueId\":null,\"orderId\":null,\"isUrgent\":0,\"vipDiscountFee\":0.0,\"itemAddFees1\":59.0,\"itemPoundage\":null,\"itemType\":1,\"proxyType\":0,\"proxyRule\":null,\"itemExtension\":{\"Location\":\"G05京昆高速1696公里980米\",\"OccurTime\":\"2020-05-2811:52:47\",\"LocationId\":\"6101\",\"LocationName\":\"陕西西安\",\"Poundage\":\"59\",\"CanProcess\":\"1\",\"Reason\":\"驾驶中型以上载客载货汽车、危险物品运输车辆以外的机动车超过规定时速10%以下的\",\"Fine\":\"0\",\"Degree\":\"0\",\"LateFine\":null,\"ViolationCode\":\"6050\",\"DocumentCode\":\"5181040000103885\",\"Payment\":\"0\",\"DeductionPay\":\"0\",\"DegreePoundage\":\"0\",\"Category\":\"私家车\",\"CollectDepartment\":\"\",\"ExcuteDepartment\":\"\",\"ExcuteLocation\":\"\",\"IllegalEntry\":\"\",\"Others\":\"0\",\"PolicePhone\":\"\",\"PunishReference\":\"\",\"Status\":\"0\",\"AddDate\":\"2020-09-1512:22:27\",\"UniqueCode\":\"39201eae34724b8894dcad71443b5ac4\",\"HistoryID\":5484536626071125446,\"ProxyRuleId\":213000,\"Privilege\":0,\"IsUsedPackage\":false,\"CooperationPrice\":59.0,\"UrgentAmount\":0.0,\"PreOrderStatus\":\"\",\"PoundageDiscount\":null,\"CardTypeId\":null,\"CarNumber\":\"川AG1T16\",\"Department\":\"四川省公安厅交通警察总队高速公路一支队四大队\",\"VioCategory\":null,\"IsMerchant\":false,\"BizDiscountAmount\":0.0,\"BeforePoundageAmount\":59.0,\"CardNum\":null,\"OilCompany\":null,\"RegionName\":null,\"Discount\":null},\"itemDiscountAmount\":0.0,\"itemId\":null,\"poundageDiscount\":null}],\"requirement\":null,\"version\":null,\"providerID\":null,\"providerType\":null,\"providerName\":null,\"userId\":\"529E8F44EB604AF181418454BB539D13\",\"userType\":null,\"userName\":null,\"orderType\":1,\"orderTypeName\":null,\"orderId\":null,\"orderIcon\":null,\"orderTitle\":null,\"orderText\":null,\"orderStatus\":0,\"orderChannel\":\"testnewwz\",\"orderCreateTime\":null,\"orderPayTime\":null,\"orderCompleteTime\":null,\"orderAmount\":59.0,\"discountAmount\":58.0,\"orderAddFees1\":null,\"orderAddFees2\":null,\"orderTotalAmount\":null,\"orderPayAmount\":null,\"Pay\":[{\"payId\":\"91981\",\"payerAcount\":null,\"payChannel\":6,\"payAmount\":58.0,\"payeeAcount\":null,\"payeeChannel\":null,\"payTransactionID\":null,\"payStatus\":\"2\",\"remark\":\"优惠券优惠58.0元\"}],\"couponAmount\":58.0,\"memberAmount\":0.0,\"vipStatus\":0,\"createVip\":false,\"vipCardAmount\":0.0}}");
        System.out.println(jsonKeyToCamel(jsonObject));
    }
}
